﻿using System;
using System.Collections.Generic;

namespace Athena.Convertible.Implementations
{
    using Serialization;
    public class DefaultTypeConvertibleProvider : ITypeConvertibleProvider
    {
        private readonly ISerializer<string> _serializer;
        public DefaultTypeConvertibleProvider(ISerializer<string> serializer)
        {
            _serializer = serializer;
        }

        public IEnumerable<TypeConvertDelegate> CreateConverts()
        {
            yield return EnumTypeConvert;
            yield return SimpleTypeConvert;
            yield return ComplexTypeConvert;
        }

        public static object EnumTypeConvert(object instance, Type conversionType)
        {
            if (instance == null || !conversionType.IsEnum)
            {
                return null;
            }
            return Enum.Parse(conversionType, instance.ToString());
        }

        public static object SimpleTypeConvert(object instance, Type conversionType)
        {
            if (instance is IConvertible && typeof(IConvertible).IsAssignableFrom(conversionType))
            {
                return Convert.ChangeType(instance, conversionType);
            }
            return null;
        }

        private object ComplexTypeConvert(object instance, Type conversionType)
        {
            return _serializer.Deserialize(instance.ToString(), conversionType);
        }
    }
}
